import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Device } from './entities/device.entity';

interface PaginationParams {
  current: number;
  pageSize: number;
  deviceType?: string;
  deviceAddress?: string;
}

@Injectable()
export class DeviceService {
  constructor(
    @InjectRepository(Device)
    private readonly deviceRepository: Repository<Device>,
  ) {}

  create(device: Partial<Device>) {
    return this.deviceRepository.save(device);
  }

  async findAll(params?: PaginationParams) {
    const {
      current = 1,
      pageSize = 10,
      deviceType,
      deviceAddress,
    } = params || {};

    // 构建查询条件
    const queryBuilder = this.deviceRepository.createQueryBuilder('device');

    if (deviceType) {
      queryBuilder.andWhere('device.deviceType = :deviceType', { deviceType });
    }

    if (deviceAddress) {
      queryBuilder.andWhere('device.deviceAddress LIKE :deviceAddress', {
        deviceAddress: `%${deviceAddress}%`,
      });
    }

    // 计算总数
    const total = await queryBuilder.getCount();

    // 分页查询
    const skip = (current - 1) * pageSize;
    const data = await queryBuilder.skip(skip).take(pageSize).getMany();

    return {
      data,
      total,
      current,
      pageSize,
      success: true,
    };
  }

  findOne(id: number) {
    return this.deviceRepository.findOneBy({ id });
  }

  update(id: number, update: Partial<Device>) {
    return this.deviceRepository.update(id, update);
  }

  remove(id: number) {
    return this.deviceRepository.delete(id);
  }

  async updateOrCreate(device: Partial<Device>) {
    const existing = await this.deviceRepository.findOneBy({
      deviceAddress: device.deviceAddress,
    });
    if (existing) {
      await this.deviceRepository.update(existing.id, device);
      return this.deviceRepository.findOneBy({ id: existing.id });
    } else {
      return this.deviceRepository.save(device);
    }
  }
}
